#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.prod'

import django
django.setup()

import datetime, hashlib, base64, requests, time
from requests_toolbelt.multipart.encoder import MultipartEncoder
from Crypto.Cipher import AES

from vouchers.models import AliDiscountCouponInfo
from postallive.models import YSPushDocumentQuest
from equity_mall.utils.qiniu_storage import pic_upload

BLOCK_SIZE = AES.block_size
pad = lambda s: s + (BLOCK_SIZE - len(s.encode()) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s.encode()) % BLOCK_SIZE)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]


def get_sign_MD5(params_str):
    md5 = hashlib.md5()  # 使用MD5加密模式
    md5.update(params_str.encode('utf-8'))  # 将参数字符串传入
    sign = md5.hexdigest()  # 完成加密并转为大写
    return sign


def encrypt(text):
    '''邮生活加密'''
    accessKey = 'HhNsYZpPQvRjtyPmHaY6KbbJsYWwdfXC'
    iv = 'EI43Xlv6Y67WT3jd'
    text = pad(text).encode()
    cipher = AES.new(key=accessKey.encode(), mode=AES.MODE_CBC, IV=iv.encode())
    encrypted_text = cipher.encrypt(text)
    return base64.b64encode(encrypted_text).decode('utf-8')


def push_ysh_syncsrttleorder():
    '''同步结算订单到邮生活'''
    print('%s: push_ysh_syncsrttleorder' % time.ctime())
    today = datetime.datetime.now()
    yesterday = today - datetime.timedelta(1)
    yesterday_begin = yesterday.strftime('%Y-%m-%d 00:00:00')
    yesterday_end = yesterday.strftime('%Y-%m-%d 23:59:59')
    secretKey = 'QRrG60h9N4xmESDX5vqEuu2TozwqbPsQ'
    url = 'http://yshsys.trial.cpsdc.com.cn/ZxptRestYshSysWEB/ysh/yshgdvirtualproduct/syncSettleOrder'
    queryset = AliDiscountCouponInfo.objects.filter(companyuser_id=64746, gmt_create__gte=yesterday_begin, gmt_create__lte=yesterday_end).values_list('out_biz_order', flat=True)
    title = 'orderNo'
    aes_title = encrypt(title)
    push_file_name = f'WYH_SETTLE_ORDER_{yesterday.strftime("%Y-%m-%d")}.csv'
    original_file_name = f'ORIGINAL_WYH_SETTLE_ORDER_{yesterday.strftime("%Y-%m-%d")}.csv'
    push_file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), f'static/{push_file_name}')
    original_file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), f'static/{original_file_name}')
    with open(push_file_path, 'w') as f:
        f.write(f'{aes_title}\n')
        for query in queryset:
            f.write(f'{encrypt(query)}\n')
    with open(original_file_path, 'w') as f:
        f.write(f'{title}\n')
        for query in queryset:
            f.write(f'{query}\n')
    requestTime = today.strftime("%Y-%m-%d %H:%M:%S")
    sign = get_sign_MD5(f'{push_file_name}{requestTime}{secretKey}')
    headers = {}
    headers['requestTime'] = requestTime
    headers['signData'] = sign
    headers['totalCount'] = str(len(queryset))
    headers['checkdate'] = today.strftime("%Y-%m-%d")
    headers['User-Agent'] = 'PostmanRuntime/7.28.2'
    body = {"file": (push_file_name, open(push_file_path, 'rb'), 'csv')}
    multipart_encoder = MultipartEncoder(body)
    headers['Content-Type'] = multipart_encoder.content_type
    response = requests.post(url, data=multipart_encoder, headers=headers)
    result = response.json()
    with open(push_file_path, 'rb')as f:
        content = f.read()
    push_file = pic_upload(content, push_file_name)
    with open(original_file_path, 'rb')as f:
        content = f.read()
    original_file = pic_upload(content, original_file_name)
    data = {}
    data['push_file'] = push_file
    data['original_file'] = original_file
    data['create_time'] = today
    data['result'] = str(result)
    YSPushDocumentQuest.objects.create(**data)
    os.remove(push_file_path)
    os.remove(original_file_path)


if __name__ == '__main__':
    push_ysh_syncsrttleorder()